#include "http_dvr_cmd.h"
#include <algorithm>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <thread>
#include <unistd.h>
#include "storage_api.h"
#include "cross_com.h"
#include "dvr_mml_svr.h"
extern CStreamerSvr g_stream_server;

http_dvr_cmd* http_dvr_cmd::pInstance_ = NULL;
http_dvr_cmd::http_dvr_cmd()
{
    jsError_["code"] = -1;
    jsError_["msg"] = "unsupport";
    MainAppUrl_ = "/api/stor";
}
http_dvr_cmd::~http_dvr_cmd()
{

}
bool http_dvr_cmd::CheckUrl(std::string url, Json::Value& v)
{
    return true;
    if (0 == MainAppUrl_.compare(url))
    {
        return true;
    }
    return false;
}


//检索录像列表
int http_dvr_cmd::PlaybackStart(Json::Value& rt, Json::Value req)
{
    time_t tm_start = req["tm_start"].asInt();
    time_t tm_end = req["tm_end"].asInt();
    time_t tm_seek = req["tm_seek"].asInt();
    int client_id = 0;
    int ch = req["ch"].asInt();
    
    int ret = STFS_PlaybackBytime(tm_start,tm_end,tm_seek,ch, client_id);
    g_stream_server.SwitchPlayMod(client_id,true);

    rt["ret"] = ret;

    return 0;
}
//检索录像列表
int http_dvr_cmd::SearchRec(Json::Value& rt, Json::Value req)
{
    int ch = req["ch"].asInt();
    time_t tm_start = 0;
    time_t tm_end = 0;
    int merge_min = 0;
    int num = 0;
    if (req.isMember("tm_date"))
    {
        int year = 0;
        int month = 0;
        int day = 0;
        string  value_str = req["tm_date"].asString();
        sscanf(value_str.c_str(), "%d-%d-%d", &year, &month, &day);

        GetDayTm_ymd(&tm_start, &tm_end, year, month, day);
    }
    else
    {
        tm_start = req["tm_start"].asInt();
        tm_end = req["tm_end"].asInt();
    }
    if (req.isMember("merge_min"))
    {   
        merge_min = req["merge_min"].asInt();
        STFS_SearchMergeTmSet(merge_min);
    }
    int rec_type = req["rec_type"].asInt();
    int buf_sz = 800 << 10;
    unsigned char* plist = new unsigned char[buf_sz];
    int client_id = 0;
    if (merge_min == 0)
    {
        int ch_bit = 1<<ch;
        num = STFS_SearchRec((char*)plist, buf_sz, tm_start, tm_end, ch_bit, rec_type,0,client_id);
        
    }
    else
        num = STFS_SearchHistoryRec(plist, buf_sz, tm_start, tm_end, ch, rec_type, client_id);
    rt["num"] = num;
    int i = 0;

    for (i = 0; i < num; i++)
    {
        Json::Value	rec_seg;
        PRECORD_SEGMENT   seg = (PRECORD_SEGMENT)(plist + sizeof(RECORD_SEGMENT) * i);
        rec_seg["ts"] = seg->tmStart;
        rec_seg["te"] = seg->tmEnd;
        rec_seg["rt"] = seg->recordType;
        rec_seg["sz"] = (uint32_t)seg->fileSize;
        rec_seg["st"] = seg->status;
        if (merge_min == 0)
        {
            rec_seg["idx"]     = seg->indexNO;      //大文件块，
            rec_seg["idx_sub"] = seg->recSegIndex; //子录像段
        }
        rt["lists"].append(rec_seg);
    }
    if (plist != nullptr)
    {
        delete[] plist;
    }
    return num;

}
bool http_dvr_cmd::run(std::string& body,
    Json::Value& v)
{
    Json::Value jsBody;

    Json::Reader reader;
    Json::Value temp;
    if (!reader.parse(body, temp))
        return false;
    jsBody = temp;
  
    try
    {
        std::cout << jsBody << std::endl;
        std::string cmd = jsBody["cmd"].asString();
        v["cmd"] = cmd;
        string value_str;
        int value = 0;
        int  ret = 0;
        int ch = 0;
        int client_id = 0;
        if (jsBody.isMember("value"))
        {
            if (!jsBody["value"].isString())
            {
                value = jsBody["value"].asInt();
            }
            fprintf(stderr, "have value type %d value %d  .\n", jsBody["value"].type(), value);
        }
        if (cmd == "set_rec_switch")
        {
            //m_func_bak->Agt_SdRecordSet(value);
            
        }
        else if (cmd == "disk_format")
        {
          //  ret = m_func_bak->Agt_SdFormat();
            v["ret"] = ret;
        }
        else if (cmd == "disk_info_get")
        {
            int status = 0;
            DiskInfo dinfo = { 0 };
            int ret = 0;

            if (-1 == access("/dev/mmcblk0", 0))
            {
                status = 0;
            }
            else
            {
                ret = STFS_GetDiskInfo((char*)&dinfo, sizeof(dinfo), "/mnt/sd");
                printf("GetDiskStat status %d isformat %d ret %d total %d free %d  .\n", dinfo.status, dinfo.isFormated, ret, dinfo.totalSpace, dinfo.recFreeSpace);

                if (0 == dinfo.isFormated)
                {
                    if (!STFS_DISK_IS_INIT("/dev/mmcblk0"))
                    {
                        printf("Double check status %d isformat %d ret %d .\n", dinfo.status, dinfo.isFormated, ret);
                        status = 2;
                    }
                    else
                    {
                        status = 1;
                    }
                }
                else
                    status = 1;
            }

            v["status"] = status;
            v["total"] = dinfo.totalSpace;
            v["free"] = (dinfo.recFreeSpace + dinfo.comPartSpace);
            v["rec_mode"] = 0;// sdInfo->recordType;
            v["rec_switch"] = 1;// sdInfo->recordEnable;
        }
        else if (cmd == "search_rec")
        {
            SearchRec(v, jsBody);
        }
        else if (cmd == "playback_start")
        {
            PlaybackStart(v, jsBody);
        }
        else if (cmd == "playback_stop")
        {
            ch = jsBody["ch"].asInt();
           
            STFS_PlaybackStop(ch, client_id);
            g_stream_server.SwitchPlayMod(client_id, false);
        }
        else if (cmd == "playback_seektm")
        {
            time_t seek_tm = jsBody["tm_utc"].asInt();
            client_id = 0;
            ch = jsBody["ch"].asInt();
            STFS_PlaybackSeekTime(seek_tm,ch, client_id);
        }
        else if (cmd == "record_start")
        {
            STFS_RecordSw(1);
        }
        else if (cmd == "record_stop")
        {
            STFS_RecordSw(0);
        }
        fprintf(stderr, "cmd %s value %d .\n", cmd.c_str(), value);
    }
    catch (const std::exception& e)
    {
        std::cout << "866" << std::endl;
        v = jsError_;
        v["msg"] = std::string(e.what());
        return false;
    }
    return true;
}